package com.micro.platform.oauth.framework.defaults;

import com.micro.platform.oauth.framework.OauthManager;
import com.micro.platform.oauth.framework.domain.OauthContext;
import com.micro.platform.oauth.framework.domain.OauthRequest;
import com.micro.platform.oauth.framework.exception.OauthException;
import com.micro.platform.oauth.framework.exception.OauthExceptionEnum;
import com.micro.platform.oauth.framework.interfaces.ITokenGranter;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class DefaultTokenGranter implements ITokenGranter {

    private Map<String, ITokenGranter> mapGrantType2TokenGranter = new HashMap<>();
    private OauthManager oauthManager;
    private String grantType = "default";

    public DefaultTokenGranter(OauthManager oauthManager) {
        this.oauthManager = oauthManager;
    }

    @Override
    public OauthContext grant(OauthRequest request) {
        if(null == request){
            throw new OauthException(OauthExceptionEnum.LoginRequestBodyIsNull);
        }
        String grantType = request.getGrantType();
        if(StringUtils.isEmpty(grantType)){
            throw new OauthException(OauthExceptionEnum.LoginRequestGrantTypeIsNull);
        }
        ITokenGranter tokenGranter = mapGrantType2TokenGranter.get(grantType);
        if(null == tokenGranter){
            throw new OauthException(OauthExceptionEnum.LoginRequestGrantTypeNotFind);
        }
        return tokenGranter.grant(request);
    }

    @Override
    public boolean registerGrant(ITokenGranter tokenGranter) {
        if(null == tokenGranter){
            return Boolean.FALSE;
        }
        if(StringUtils.isEmpty(tokenGranter.getGrantType())){
            return Boolean.FALSE;
        }
        mapGrantType2TokenGranter.put(tokenGranter.getGrantType(),tokenGranter);
        return true;
    }

    @Override
    public String getGrantType() {
        return grantType;
    }
}
